package cc.rengu.igas.channel.upgw.core.service.trans;

import cc.rengu.igas.channel.upgw.core.service.base.UpgwBaseService;
import cc.rengu.igas.channel.upgw.common.constant.UpgwHeaderConstant;
import cc.rengu.igas.channel.upgw.common.constant.UpgwParamConstant;
import cc.rengu.igas.channel.upgw.common.constant.UpgwTreeNodeConstant;
import cc.rengu.igas.channel.upgw.common.enums.UpgwRespCodeEnum;
import cc.rengu.igas.channel.upgw.facade.bean.OrigTxnResultInfo;
import cc.rengu.igas.channel.upgw.facade.request.UpgwPersonalGatewayTransStateQueryRequest;
import cc.rengu.igas.channel.upgw.facade.response.UpgwPersonalGatewayTransStateQueryResponse;
import cc.rengu.jradp.schedule.ScheduleImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

/**
 * @author wukefan
 * @version 1.0.0
 * @date 2020/10/7 9:18
 */
public class UpgwPersonalGatewayTransStateQueryService extends UpgwBaseService {

    @Override
    protected Object beforeBizProcess() throws Exception {
        UpgwPersonalGatewayTransStateQueryRequest request = new UpgwPersonalGatewayTransStateQueryRequest();
        ConvertUtil.convertOutput(request);
        return request;
    }

    @Override
    protected BizResponse callBizService(Object request) throws Exception {

        XmlTreeUtil xmlTree = new XmlTreeUtil();
        UpgwPersonalGatewayTransStateQueryRequest upgwPersonalGatewayTransStateQueryRequest = (UpgwPersonalGatewayTransStateQueryRequest) request;
        BizResponse<UpgwPersonalGatewayTransStateQueryResponse> bizResponse = new BizResponse<>();
        UpgwPersonalGatewayTransStateQueryResponse response = new UpgwPersonalGatewayTransStateQueryResponse();
        if (!verifyRequest(upgwPersonalGatewayTransStateQueryRequest)) {
            response.setRespCode(OltpRpcdEnum.PARAM_IS_EMPTY_OR_NULL.getRespCode());
            response.setRespDesc(OltpRpcdEnum.PARAM_IS_EMPTY_OR_NULL.getRespDesc());
            bizResponse.setResult(response);
            return bizResponse;
        }

        /* 将请求赋值到xml中 */
        requestToXMLTree(xmlTree, upgwPersonalGatewayTransStateQueryRequest);

        /* TODO 演示环境默认返回成功 START */
        if (AppParamConstant.DEFAULT_ENV.equals(AppParamConstant.APPLICATION_ENV)) {
            rglog.info("演示环境默认返回成功");
            response.setRespCode(UpgwRespCodeEnum.ACCEPT_SUCCESS.getRespCode());
            response.setRespDesc(UpgwRespCodeEnum.ACCEPT_SUCCESS.getRespDesc());
            bizResponse.setResult(response);
            return bizResponse;
        }
        /* TODO 演示环境默认返回成功 END */

        try {
            int retCode = schedule.callService(UpgwParamConstant.UPGW_COMMUNICATION_SVC_NM, UpgwParamConstant.UPGW_COMMUNICATION_SVC_LABEL);
            /*判断retCode返回值*/
            /*通讯成功*/
            if (ScheduleImpl.SERVICE_SUCCESS == retCode) {
                /*判断状态码*/
                String status = xmlTree.getXmlTreeStringValue(UpgwHeaderConstant.STATUS);
                if (UpgwParamConstant.STATUS_SUCC.equals(status)) {
                    rglog.debug("调用通道业务成功");
                    //通道调用成功的应答处理
                    //成功 转换成功应答码为统一应答码，调用方根据返回00000000判断业务是否成功
                    response.setRespCode(OltpRpcdEnum.TRANS_SUCCESS.getRespCode());
                    response.setRespDesc(OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());

                    response.setAcctFinishDate(xmlTree.getXmlTreeStringValue(UpgwTreeNodeConstant.ENTACCTFINISHTM));
                    OrigTxnResultInfo origTxnResultInfo = new OrigTxnResultInfo();
                    origTxnResultInfo.setOrigRespCode(xmlTree.getXmlTreeStringValue(UpgwTreeNodeConstant.BIZINF_ORISYSRTNCD));
                    origTxnResultInfo.setOrigRespDesc(xmlTree.getXmlTreeStringValue(UpgwTreeNodeConstant.BIZINF_ORISYSRTNDESC));
                    origTxnResultInfo.setOrigSettleDate(xmlTree.getXmlTreeStringValue(UpgwTreeNodeConstant.ORISETTLMTDT));
                    origTxnResultInfo.setOrigSettleInfo(xmlTree.getXmlTreeStringValue(UpgwTreeNodeConstant.BIZINF_ORISETTLMTINF));
                    String origTxnStatus = xmlTree.getXmlTreeStringValue(UpgwTreeNodeConstant.BIZINF_TRXSTATUS);
                    switch (origTxnStatus) {
                        case "0":
                        case "3":
                            //成功
                            origTxnResultInfo.setOrigTxnStatus("0");
                            break;
                        case "1":
                            //失败
                            origTxnResultInfo.setOrigTxnStatus("1");
                            break;
                        case "2":
                            //超时
                            origTxnResultInfo.setOrigTxnStatus("2");
                            break;
                        default:
                            //默认超时
                            origTxnResultInfo.setOrigTxnStatus("2");
                            break;
                    }
                    response.setOrigTxnResultInfo(origTxnResultInfo);
                    bizResponse.setResult(response);
                } else if (UpgwParamConstant.STATUS_FAIL.equals(status)) {
                    rglog.debug("调用通道业务失败");
                    //通过判断应答码，判定交易状态是否为超时;ESB超时错误码为E000A703
                    String code = xmlTree.getXmlTreeStringValue(UpgwHeaderConstant.CODE);
                    if (StringUtil.isNullorEmpty(code)) {
                        response.setRespCode(UpgwParamConstant.DEFAULT_ERR_CODE);
                    } else if (UpgwParamConstant.ESB_TIME_OUT_E000A703.equals(code)) {
                        response.setRespCode(OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespCode());
                    } else {
                        response.setRespCode(code);
                    }
                    String desc = xmlTree.getXmlTreeStringValue(UpgwHeaderConstant.DESC);
                    if (StringUtil.isNullorEmpty(desc)) {
                        response.setRespDesc(UpgwParamConstant.DEFAULT_ERR_DESC);
                    } else {
                        response.setRespDesc(desc);
                    }
                    bizResponse.setResult(response);
                } else {
                    rglog.debug("调用通道业务未知");
                    String code = xmlTree.getXmlTreeStringValue(UpgwHeaderConstant.CODE);
                    if (StringUtil.isNullorEmpty(code)) {
                        response.setRespCode(OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespCode());
                    } else {
                        response.setRespCode(code);
                    }
                    String desc = xmlTree.getXmlTreeStringValue(UpgwHeaderConstant.DESC);
                    if (StringUtil.isNullorEmpty(desc)) {
                        response.setRespDesc(OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespCode());
                    } else {
                        response.setRespDesc(desc);
                    }
                    bizResponse.setResult(response);
                }
            } else if (ScheduleImpl.SERVICE_TIMEOUT == retCode) {
                //调用超时 赋值应答
                rglog.error("callService {} 失败！返回值={}", UpgwParamConstant.UPGW_COMMUNICATION_SVC_NM, retCode);
                response.setRespCode(OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespCode());
                response.setRespDesc(OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespDesc());
                bizResponse.setResult(response);
                return bizResponse;
            } else {
                //调用明确失败
                rglog.error("callService {} 失败！返回值={}", UpgwParamConstant.UPGW_COMMUNICATION_SVC_NM, retCode);
                response.setRespCode(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode());
                response.setRespDesc(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
                bizResponse.setResult(response);
                return bizResponse;
            }
        } catch (Exception e) {
            //失败赋值应答码为明确失败及应答消息直接退出
            rglog.error("{}", StringUtil.ExceptionToString(e));
            response.setRespCode(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode());
            response.setRespDesc(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            bizResponse.setResult(response);
            return bizResponse;
        }
        bizResponse.setResult(response);
        return bizResponse;
    }

    private void requestToXMLTree(XmlTreeUtil xmlTree, UpgwPersonalGatewayTransStateQueryRequest upgwPersonalGatewayTransStateQueryRequest) throws Exception {
        /*公共报文信息*/
        /*请求方机构代码*/
        xmlTree.setXmlTreeStringValue(UpgwHeaderConstant.BRANCH_ID, upgwPersonalGatewayTransStateQueryRequest.getHeader().getInstId() + UpgwParamConstant.DEFAULT_VIRTUAL_INST_ID);
        /*服务渠道代码*/
        xmlTree.setXmlTreeStringValue(UpgwHeaderConstant.CHANNEL_ID, UpgwParamConstant.CHANNEL_ID);
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getHeader().getFrontChannelId())) {
            xmlTree.setXmlTreeStringValue(UpgwHeaderConstant.CHANNEL_ID, upgwPersonalGatewayTransStateQueryRequest.getHeader().getFrontChannelId());
        }
        /*请求方系统代码*/
        xmlTree.setXmlTreeStringValue(UpgwHeaderConstant.REQUESTER_ID, UpgwParamConstant.REQUEST_ID);
        /*ESB服务码*/
        xmlTree.setXmlTreeStringValue(UpgwHeaderConstant.SERVICE_ID, upgwPersonalGatewayTransStateQueryRequest.getHeader().getTxnNum());
        /*请求方服务流水号*/
        xmlTree.setXmlTreeStringValue(UpgwHeaderConstant.SERVICE_SN, upgwPersonalGatewayTransStateQueryRequest.getHeader().getTraceNo());
        /*请求方服务时间*/
        xmlTree.setXmlTreeStringValue(UpgwHeaderConstant.SERVICE_TIME, upgwPersonalGatewayTransStateQueryRequest.getHeader().getTransDate() + upgwPersonalGatewayTransStateQueryRequest.getHeader().getTransTime());
        /*版本号*/
        xmlTree.setXmlTreeStringValue(UpgwHeaderConstant.VERSION_ID, UpgwParamConstant.VERSION_ID);
        /*查询功能标识*/
        xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.INQFUNCTION, UpgwParamConstant.INQFUNCTION_GATEWAY);
        /*原ESB流水*/
        xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.ORI_SERVICE_SN, upgwPersonalGatewayTransStateQueryRequest.getOrigTraceNo());
        /*原交易时间*/
        xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.ORI_SERVICE_DATE, upgwPersonalGatewayTransStateQueryRequest.getOrigTransDate());
        /*初始交易类型*/
        xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.INITRXTP, UpgwParamConstant.INITRXTP_PERSONAL);


        /*报文初始发起机构标识*/
        xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.ORIISSRID, upgwPersonalGatewayTransStateQueryRequest.getOriIssrId());
        /*接受方账户*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getOrigRecvAcctInfo())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RCVERINF_RCVERACCTID, upgwPersonalGatewayTransStateQueryRequest.getOrigRecvAcctInfo());
        }
        /*签约协议号*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRecvSignNo())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RCVERINF_SGNNO, upgwPersonalGatewayTransStateQueryRequest.getRecvSignNo());
        }
        /*接收信息-IP*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getReceiveInfo().getIpAddr())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RCVERINF_SOURCEIP, upgwPersonalGatewayTransStateQueryRequest.getReceiveInfo().getIpAddr());
        }
        /*接收信息-MAC*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getReceiveInfo().getMacAddr())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RCVERINF_MAC, upgwPersonalGatewayTransStateQueryRequest.getReceiveInfo().getMacAddr());
        }
        /*接收信息-设备号*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getReceiveInfo().getDevId())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RCVERINF_DEVID, upgwPersonalGatewayTransStateQueryRequest.getReceiveInfo().getDevId());
        }
        /*设备型号*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceMode())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_DEVICEMODE, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceMode());
        }
        /*设备语言*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceLanguage())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_DEVICELANGUAGE, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceLanguage());
        }
        /*GPS 位置*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceLocation())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_EXTENSIVEDEVICELOCATION, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceLocation());
        }
        /*SIM 卡号码*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceNo())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_DEVICENUMBER, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceNo());
        }
        /*SIM 卡数量*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceSimNum())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_DEVICESIMNUMBER, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getDeviceSimNum());
        }
        /*账户 ID*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getAccountId())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_ACCOUNTIDHASH, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getAccountId());
        }
        /*风险评分*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getRiskScore())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_RISKSCORE, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getRiskScore());
        }
        /*原因码*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getRiskReasonCode())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_RISKREASONCODE, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getRiskReasonCode());
        }
        /*收单端用户注册日期*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getMchntUsrRgstrTm())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_MCHNTUSRRGSTRTM, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getMchntUsrRgstrTm());
        }
        /*收单端注册账户邮箱地址*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getMchntUsrRgstrEmail())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_MCHNTUSRRGSTREMAIL, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getMchntUsrRgstrEmail());
        }
        /*收货省*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getRcvProvince())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_RCVPROVINCE, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getRcvProvince());
        }
        /*收货市*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getRcvCity())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_RCVCITY, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getRcvCity());
        }
        /*商品类型*/
        if (!StringUtil.isNullorEmpty(upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getGoodsClass())) {
            xmlTree.setXmlTreeStringValue(UpgwTreeNodeConstant.RSKINF_GOODSCLASS, upgwPersonalGatewayTransStateQueryRequest.getRiskInfo().getGoodsClass());
        }

    }

    private boolean verifyRequest(UpgwPersonalGatewayTransStateQueryRequest upgwPersonalGatewayTransStateQueryRequest) {
        String oriIssrId = upgwPersonalGatewayTransStateQueryRequest.getOriIssrId();
        String origTraceNo = upgwPersonalGatewayTransStateQueryRequest.getOrigTraceNo();
        String origTransDate = upgwPersonalGatewayTransStateQueryRequest.getOrigTransDate();

        if (StringUtil.isNullorEmpty(oriIssrId) ||
                StringUtil.isNullorEmpty(origTraceNo) ||
                StringUtil.isNullorEmpty(origTransDate)) {
            //失败赋值应答码为明确失败及应答消息直接退出
            rglog.error("缺少一个或多个业务参数！");
            return false;
        }
        rglog.trace("检查请求通过");
        return true;
    }

    @Override
    protected void afterBizProcess(BizResponse response) throws Exception {
        UpgwPersonalGatewayTransStateQueryResponse upgwPersonalGatewayTransStateQueryResponse = (UpgwPersonalGatewayTransStateQueryResponse) response.getResult();
        ConvertUtil.convertInput(upgwPersonalGatewayTransStateQueryResponse);
    }
}
